package xhe.openapi.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import xhe.entities.ApiEntity;
import xhe.inf.service.CommonService;
import xhe.lib.date.TimeStamp;

@RestController
public class OpenAPIController {

	@Autowired
	private DiscoveryClient iClient;

	@Autowired
	private CommonService iService;

	@RequestMapping(value = "xhe/openapi")
	public void openAPI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 添加请求头,解决跨域问题
		// response.addHeader("Access-Control-Allow-Origin", "*");

		// 声明请求
		ApiEntity apiEntity = new ApiEntity();

		// 查询
		apiEntity = iService.openAPI(request, response);

		PrintWriter out = response.getWriter();
		// out.println("[\"" + Gzip.gZip(apiEntity.getResponse()) + "\"]");

		out.println(apiEntity.getResponse());
	}

//	@Autowired
	@RequestMapping(value = "xhe/discovery", method = RequestMethod.GET)
	public Object discovery() {
		List<String> list = iClient.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = iClient.getInstances("xheOpenAPI");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.iClient;
	}

	@RequestMapping(value = "xhe/auth")
	public void auth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		System.out.println("------------------鉴权开始----------------");
		String strSign = "";
		long stamp = 0;

		// 添加请求头,解决跨域问题
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Headers", "appid,timestamp,sign");
		// 设置响应内容类型
		response.setContentType("application/json; charset=utf-8");

		try {
			Map<String, String> oHeaders = new LinkedHashMap<String, String>();
			Enumeration<String> headerNames = request.getHeaderNames();
			// hasMoreElements = 检测Enumeration中是否还有元素，有则返回true 继续循环，无则返回false 结束循环

			while (headerNames.hasMoreElements()) {
				// nextElement = 获取Enumeration中的下一个元素
				String headerName = headerNames.nextElement();
				// getHeader = 根据请求头名字获取请求头内容
				String headerValue = request.getHeader(headerName);

				oHeaders.put(headerName, headerValue);

				System.out.println(headerName + ":" + headerValue);
			}

//			System.out.println("Request:[appid:" + oHeaders.get("appid") + ",timestamp:" + oHeaders.get("timestamp")
//					+ ",sign:" + oHeaders.get("sign") + "]");

			if (oHeaders.get("appid").equals("null") || oHeaders.get("timestamp").equals("null")
					|| oHeaders.get("sign").equals("null")) {
				response.setStatus(404);
			} else {

				// 认证Flag
				boolean responseFlag = true;

				strSign = DigestUtils.md5Hex(oHeaders.get("appid") + oHeaders.get("timestamp"));

				if (!oHeaders.get("sign").equals(strSign)) {
					responseFlag = false;
				}

				stamp = TimeStamp.compareMinutes(oHeaders.get("timestamp"), new Date());

				if (stamp > 3) {
					responseFlag = false;
				}

				// 认证逻辑代码

				if (responseFlag) {
					// 认证成功
					response.setStatus(200);
				} else {
					// 认证失败
					response.setStatus(401);
				}

//				String strRequest = xhe.lib.data.Util.getRequest(request.getInputStream());
//
//				if (StringUtils.isNotEmpty(strRequest)) {
//					System.out.println(strRequest);
//					if (strRequest.contains("'")) {
//						response.setStatus(403);
//					} else if (strRequest.contains("<")) {
//						response.setStatus(403);
//					} else if (strRequest.contains(">")) {
//						response.setStatus(403);
//					} else if (strRequest.contains("alert")) {
//						response.setStatus(403);
//					} else if (strRequest.contains("script")) {
//						response.setStatus(403);
//					} else if (strRequest.contains(";")) {
//						response.setStatus(403);
//					}
//				}
			}

		} catch (Exception ex) {
			response.setStatus(500);
			ex.printStackTrace();
		}

		// System.out.println("Response:[sign:" + strSign + ",stamp:" + stamp +
		// ",status:" + response.getStatus() + "]");
		System.out.println("------------------鉴权结束----------------");
		// 输出返回结果
		PrintWriter out = response.getWriter();
		out.println(response.getStatus());
	}

}
